package com.icoolkj.mall.order.service.impl;

import com.icoolkj.mall.common.Result;
import com.icoolkj.mall.common.exception.BusinessException;
import com.icoolkj.mall.order.feign.AccountServiceFeignClient;
import com.icoolkj.mall.order.feign.InventoryServiceFeignClient;
import com.icoolkj.mall.order.feign.ProductServiceFeignClient;
import com.icoolkj.mall.order.feign.dto.AccountRequest;
import com.icoolkj.mall.order.feign.dto.InventoryRequest;
import com.icoolkj.mall.order.feign.dto.ProductResponse;
import com.icoolkj.mall.order.mapper.OrderMapper;
import com.icoolkj.mall.order.model.Order;
import com.icoolkj.mall.order.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/01/16 14:44
 */
@Service
public class OrderServiceImpl implements OrderService {

    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AccountServiceFeignClient accountServiceFeignClient;

    @Autowired
    private ProductServiceFeignClient productServiceFeignClient;

    @Autowired
    private InventoryServiceFeignClient inventoryServiceFeignClient;

    @Override
    @GlobalTransactional(name = "createOrder", rollbackFor = Exception.class)
    //@Transactional
    public Result<?> createOrder(Long userId, Long productId, Integer orderQuantity) {

        logger.info("[reduceBalance] currenet XID: {}", RootContext.getXID());

        if(orderQuantity == null){
            throw new BusinessException("The order quantity cannot be empty.");
        }
        //deduct inventory
        InventoryRequest inventoryRequest = new InventoryRequest();
        inventoryRequest.setProductId(productId);
        inventoryRequest.setInventoryQuantity(orderQuantity);
        //RestTemplate 远程调用
        //String inventoryUrl = "http://localhost:8081/api/inventory/reduce-inventory";
        //整合 Nacos + LoadBalancer，可以使用库存的微服务名称 icoolkj-mall-inventory 代替 localhost:8081
//        String inventoryUrl = "http://icoolkj-mall-inventory/api/inventory/reduce-inventory";
//        int inventoryCode = restTemplate.postForObject(inventoryUrl, inventoryRequest, Result.class).getCode();
        //OpenFeign 远程调用库存服务
        int inventoryCode = inventoryServiceFeignClient.reduceInventory(inventoryRequest).getCode();
        if(inventoryCode == Result.FAIL){
            throw new BusinessException("inventory not enough.");
        }

        // 获取商品单价
        //String getPriceProductUrl = "http://localhost:8080/api/product/get-price-product?productId=" + productId;
        //整合 Nacos + LoadBalancer，可以使用商品的微服务名称 icoolkj-mall-product 代替 localhost:8080
//        String getPriceProductUrl = "http://icoolkj-mall-product/api/product/get-price-product?productId=" + productId;
//        // 使用泛型解析嵌套数据
//        ParameterizedTypeReference<Result<ProductResponse>> responseType =
//                new ParameterizedTypeReference<Result<ProductResponse>>() {};
//        ResponseEntity<Result<ProductResponse>> responseEntity =
//                restTemplate.exchange(getPriceProductUrl, HttpMethod.GET, null, responseType);
//
//        // 获取返回结果
//        Result<ProductResponse> result = responseEntity.getBody();

        //OpenFeign 远程调用商品服务
        Result<ProductResponse> result = productServiceFeignClient.getPriceProduct(productId);
        BigDecimal orderCost = null;
        if(result.getCode() == Result.SUCCESS){
            ProductResponse productResponse = result.getData();
            if (productResponse != null && productResponse.getProductPrice() != null) {
                orderCost= productResponse.getProductPrice().multiply(new BigDecimal(orderQuantity));
            }
        }
        if(orderCost == null){
            throw new BusinessException("product price wrong, please check the product price.");
        }
        AccountRequest accountRequest = new AccountRequest();
        accountRequest.setUserId(userId);
        accountRequest.setOrderCost(orderCost);
        //RestTemplate远程调用
        //String account_url = "http://localhost:8083/api/account/reduce-balance";
        //整合 Nacos + LoadBalancer，可以使用账户的微服务名称 icoolkj-mall-account 代替 localhost:8083
//        String account_url = "http://icoolkj-mall-account/api/account/reduce-balance";
//        int accountCode = restTemplate.postForObject(account_url, accountRequest, Result.class).getCode();
        //OpenFeign 远程调用账户服务
        Integer accountCode = accountServiceFeignClient.reduceBalance(accountRequest).getCode();
        if (accountCode == Result.FAIL) {
            throw new BusinessException("balance not enough");
        }

        //save order
        Order order = new Order();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setOrderQuantity(orderQuantity);
        order.setOrderCost(orderCost);
        order.setCreateTime(new Date());
        orderMapper.saveOrder(order);
        return Result.ok(order);

    }
}
